var models = require('../models');
var Reply = models.Reply;
var Topic = models.Topic;
var EventProxy = require('eventproxy');

exports.create = function (req, res, next) {
	var topicId = req.body.topicId,
		content = req.body.content;
	console.log(topicId);
	console.log(content);

	var ep = new EventProxy();
	ep.fail(next);
	ep.on('create_error', function (msg) {
		res.json({ result: 'fail', msg: msg });
	});
	if (!topicId || !content) {
		return ep.emit('create_error', '信息不能为空！');
	}
	if (!req.session.user) {
		return ep.emit('create_error', '没有权限！');
	}
	Topic.findById(topicId, ep.done(function (topic) {
		if (!topic) return ep.emit('create_error', '主题不存在');
		var reply = new Reply();
		reply.content = content;
		reply.authorId = req.session.user._id;
		reply.topicId = topic._id;
		reply.save(ep.done(function () {
			res.json({ result: 'success' });
		}));
	}))
}